package com.school.lab.common.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.school.lab.common.dao.GenericDao;



/**
 * Data access object (DAO) for domain model
 * 
 * @author MyEclipse Persistence Tools
 */
public class GenericDaoHibernateImpl<T, ID extends Serializable> extends
		HibernateDaoSupport implements GenericDao<T, ID> {
	/**
	 * 
	 */
	private Class<T> persistentClass;

	/**
	 * 
	 */
	@SuppressWarnings("unchecked")
	public GenericDaoHibernateImpl() {
		this.persistentClass = (Class<T>) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
	}

	/**
	 * Constructor that takes in a class to see which type of entity to persist
	 * 
	 * @param persistentClass
	 *            the class type you'd like to persist
	 */
	public GenericDaoHibernateImpl(final Class<T> persistentClass) {
		this.persistentClass = persistentClass;
	}

	/**
	 * Persistent the entity to database
	 * 
	 * @param entity
	 */
	@SuppressWarnings("unchecked")
	public T save(T entity) {
		return (T) getHibernateTemplate().save(entity);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.locisoft.common.dao.GenericDao#saveOrUpdate(java.lang.Object)
	 */
	public void saveOrUpdate(T entity) {
		getHibernateTemplate().saveOrUpdate(entity);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.locisoft.common.dao.GenericDao#update(java.lang.Object)
	 */
	public void update(T entity) {
		getHibernateTemplate().update(entity);
	}

	/**
	 * Delete the given persistent instance.
	 */
	public void delete(ID id) {
		getHibernateTemplate().delete(this.get(id));
	}

	/**
	 * Get entity by id
	 * 
	 * @param id
	 */
	@SuppressWarnings("unchecked")
	public T get(ID id) {
		return (T) getHibernateTemplate().get(this.persistentClass, id);
	}

	/**
	 * Load entity by id
	 * 
	 * @param id
	 */
	@SuppressWarnings("unchecked")
	public T load(ID id) {
		return (T) getHibernateTemplate().load(this.persistentClass, id);
	}

	/**
	 * 
	 */
	@SuppressWarnings("unchecked")
	public List<T> loadAll() {
		return (List<T>) getHibernateTemplate().loadAll(this.persistentClass);
	}

	/**
	 * Remove all objects from the org.hibernate.Session cache, and cancel all
	 * pending saves, updates and deletes
	 */
	public void clear() {
		getHibernateTemplate().clear();
	}

	/**
	 * Flush all pending saves, updates and deletes to the database.
	 */
	public void flush() {
		getHibernateTemplate().flush();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.locisoft.common.dao.GenericDao#exists(java.io.Serializable)
	 */
	public boolean exists(ID id) {
		return false;
	}

}
